Imports System.Web.UI
Imports System.Text
Imports Objects.Security.Cryptography
Imports Objects.EmployeeInfo
Imports System.Web
Imports System.IO
Imports System.Configuration
Imports System.Net.NetworkInformation
Imports System.Globalization
Imports System.Threading
Imports CObject

Public Structure HistoryItem
    Private msPageURL As String
    Private msPageName As String
    Public Sub New(ByVal PageURL As String, ByVal PageName As String)
        msPageURL = PageURL
        msPageName = PageName
    End Sub
    Public ReadOnly Property PageURL() As String
        Get
            Return msPageURL
        End Get

    End Property
    Public ReadOnly Property PageName() As String
        Get
            Return msPageName
        End Get

    End Property
End Structure
''' -----------------------------------------------------------------------------
''' Project	 : Objects
''' Class	 : cPage
''' 
''' -----------------------------------------------------------------------------
''' <summary>
''' Every page we write should inherit from this page
''' </summary>
''' <remarks>
''' This gives us a way to affect all pages from one place in our code
''' </remarks>
''' -----------------------------------------------------------------------------
Public Class cPage
    Inherits Page

    Public Const INTERNAL_MAIN_PAGE As String = "/default.aspx"
    Public Const INTERNAL_HOME_PAGE As String = "/default.aspx"

    Public Const HOME_PAGE As String = "/default.aspx"


    Private Const STR_LdapadamemailAttrib As String = "ldap.adam.emailAttrib"

    Public Const TIMEOUT As Integer = 90
    Public Const SECURITY_PAGE_NO_SECOBJECTID As String = "/SecurityRedirect/SecurityRedirect.aspx?SecObject=0"
    Public Const SECURITY_REDIRECT_PAGE As String = "~/SecurityRedirect/SecurityRedirect.aspx"

    Private moCurrentUser As Employee
    Const MAX_MS As Long = 9999
    Const MIN_MS As Long = 0


    Public Function SecurityRedirectURL(ByVal SecObjectID As Integer) As String
        Dim loSettings As Utility.Settings = New Utility.Settings(ConnectionServer.Connection.SourceDataBase.CMT)
        Return SECURITY_REDIRECT_PAGE & "?SecObject=" & SecObjectID.ToString
    End Function

    Public ReadOnly Property CultureInfo() As CultureInfo
        Get
            Try
                If System.Web.HttpContext.Current.Request.UserLanguages Is Nothing Then
                    Return USCulture
                Else
                    Return Globalization.CultureInfo.CreateSpecificCulture(System.Web.HttpContext.Current.Request.UserLanguages(0))
                End If
            Catch e As SystemException
                Return USCulture
            End Try
        End Get
    End Property
    Public ReadOnly Property USCulture() As CultureInfo
        Get
            Return Globalization.CultureInfo.CreateSpecificCulture("en-us")
        End Get
    End Property
    Public Function USDateString(ByVal dtDate As DateTime) As String
        Return dtDate.ToString("d", USCulture)
    End Function
    Public Enum StringFormat
        ShortDate
        LongDate
        LongDateShortTime
        LongDateLongTime
        GeneralDateTime
        Month
        RoundTrip
        Sortable
        Universal
        YearMonth
        LongTime
        ShortTime
    End Enum

    Public Function DateString(ByVal dtDate As DateTime, Optional ByVal f As StringFormat = StringFormat.ShortDate, Optional ByVal pCultureInfo As CultureInfo = Nothing) As String
        Dim lsDate As String = String.Empty
        Dim lCulture As CultureInfo
        If pCultureInfo Is Nothing Then
            lCulture = CultureInfo
        Else
            lCulture = pCultureInfo
        End If


        Select Case f
            Case StringFormat.GeneralDateTime
                lsDate = dtDate.ToString("g", lCulture)
            Case StringFormat.LongDate
                lsDate = dtDate.ToString("D", lCulture)
            Case StringFormat.LongDateLongTime
                lsDate = dtDate.ToString("F", lCulture)
            Case StringFormat.LongDateShortTime
                lsDate = dtDate.ToString("f", lCulture)
            Case StringFormat.Month
                lsDate = dtDate.ToString("m", lCulture)
            Case StringFormat.RoundTrip
                lsDate = dtDate.ToString("r", lCulture)
            Case StringFormat.ShortDate
                lsDate = dtDate.ToString("d", lCulture)
            Case StringFormat.Sortable
                lsDate = dtDate.ToString("s", lCulture)
            Case StringFormat.Universal
                lsDate = dtDate.ToString("U", lCulture)
            Case StringFormat.YearMonth
                lsDate = dtDate.ToString("Y", lCulture)
            Case StringFormat.LongTime
                lsDate = dtDate.ToString("T", lCulture)
            Case StringFormat.ShortTime
                lsDate = dtDate.ToString("t", lCulture)
        End Select
        Return lsDate
    End Function


    Protected Overrides Sub InitializeCulture()


        Thread.CurrentThread.CurrentCulture = CultureInfo
        Thread.CurrentThread.CurrentUICulture = CultureInfo
        MyBase.InitializeCulture()

    End Sub
    Private Sub GetCredientials()


        Dim lbRequest As Boolean = False
        Try
            lbRequest = (Context.Request.LogonUserIdentity.AuthenticationType <> "Negotiate" And Context.Request.LogonUserIdentity.AuthenticationType <> "NTLM")
        Catch ex As Exception
            lbRequest = True
        End Try

        If User.Identity.Name.ToUpper.StartsWith("IUSR_") Or User.Identity.Name = String.Empty Or lbRequest Then
            Context.Response.ClearHeaders()
            Context.Response.StatusCode = 401
            Context.Response.AppendHeader("WWW-Authenticate", "Negotiate")
            Context.Response.AppendHeader("WWW-Authenticate", "NTLM")
            Context.Response.Buffer = False
            Context.Response.End()
        End If
    End Sub


    Protected Sub LoadUser()
        GetCredientials()
        Dim lsuser As String = Request.LogonUserIdentity.Name.ToLower

        'If CurrentUser.NetworkID.ToLower = lsuser Or CurrentUser.IsOverriden Then
        Response.Expires = 0
        Return
    End Sub


    Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Init

        If Not Request.QueryString("Crypt") Is Nothing Then
            Dim loCrypt As Encryption = New Encryption
            Dim lsQS As String = loCrypt.DecryptString64(Request.Url.Query.Replace("?Crypt=", ""))
            Server.Transfer(Page.Request.Url.LocalPath & lsQS, False)
            Exit Sub
        Else
            TestForSQLInjection(Request.Url.Query.ToString.ToLower)
        End If

        LoadUser()


    End Sub

    Public Function TestForSQLInjection(ByVal psSQL As String) As String

        Dim rexSql As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("/exec(\s|\+)+(s|x)p\w+/ix")
        Dim rexSql2 As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("(\-\-)")
        Dim rexSql3 As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("(union)") 'checking for the union keyword
        Dim rexSql4 As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("(select)") 'checking for the select keyword
        Dim rexSql5 As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("(from)") 'checking for the from keyword
        Dim rexSql6 As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("(where)") 'checking for the where keyword
        Dim rexSql7 As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("(alter)") 'checking for the alter keyword
        Dim rexSql8 As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("(delete)") 'checking for the delete keyword
        Dim rexSql9 As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("(table)") 'checking for the table keyword

        If Not rexSql.Match(psSQL).Success And Not rexSql2.Match(psSQL).Success And Not rexSql3.Match(psSQL).Success _
            And Not rexSql4.Match(psSQL).Success And Not rexSql5.Match(psSQL).Success And Not rexSql6.Match(psSQL).Success _
            And Not rexSql7.Match(psSQL).Success And Not rexSql8.Match(psSQL).Success And Not rexSql9.Match(psSQL).Success Then

            Return psSQL

        End If

        Throw New Exception("SQL Injection attack possible with:" & psSQL)
    End Function

    Public ReadOnly Property CurrentUser() As EmployeeInfo.Employee
        Get
            Dim lsUser As String = User.Identity.Name
            If moCurrentUser Is Nothing Then
                Dim bCacheUnavailable As Boolean = False
                'Test to see if the Cache is availalbe.  It will not be for Ajax Calls.
                Try
                    moCurrentUser = CType(Cache.Get(lsUser), Employee)
                    If Not moCurrentUser Is Nothing Then
                        If moCurrentUser.NetworkID.ToLower <> lsUser.ToLower Then
                            moCurrentUser = Nothing
                        End If
                    End If
                Catch e As Exception
                    bCacheUnavailable = True
                End Try
                'If the Cahce was unavailable or the user object was not Cached,  we need to go get it.
                If moCurrentUser Is Nothing Then

                    Dim loSettings As Utility.Settings = New Utility.Settings()
                    Dim lsORUser As String = String.Empty
                    Dim loEmp As Employee = Nothing
                    If Not loSettings("UserOverride") Is Nothing AndAlso loSettings("UserOverride").Length > 0 Then
                        lsORUser = loSettings("UserOverride")
                        Dim locoll As CCollection = New CCollection(New Employee, "NetworkID='" & lsORUser & "'")
                        loEmp = CType(locoll.DataObject, Employee)
                        If loEmp Is Nothing Then
                            GetCredientials()
                            loEmp = New Employee(Context.Request.LogonUserIdentity)
                        End If
                    Else
                        GetCredientials()
                        loEmp = New Employee(Context.Request.LogonUserIdentity)
                    End If

                    'If the user if found the write to currentUser
                    If Not loEmp Is Nothing Then
                        moCurrentUser = loEmp
                        If Not bCacheUnavailable Then
                            'If the Cache is available write it to Cache
                            Context.Cache.Add(lsUser, loEmp, Nothing, Date.MaxValue, TimeSpan.FromMinutes(30), Caching.CacheItemPriority.Default, Nothing)
                        End If
                    Else
                        'If the user is not found the throw an error
                        Response.Redirect("/errors/lockout.aspx")
                    End If
                End If
                If moCurrentUser.IsMember(1) Then
                    'If the user is Admin then check for Sec_Overrrides
                    Dim lsOverrideGUI As String = moCurrentUser.Sec_OverrideGUI

                    'Do not user Cache when override in the user
                    If lsOverrideGUI <> moCurrentUser.GUI Then
                        moCurrentUser = New Employee(lsOverrideGUI)
                        Cache.Item(lsUser) = moCurrentUser
                        moCurrentUser.IsOverriden = True
                    End If


                End If
            End If

            Return moCurrentUser

        End Get
    End Property


    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' Adds generic client sided script
    ''' </summary>
    ''' <param name="e"></param>
    ''' <remarks>
    ''' </remarks>   
    ''' -----------------------------------------------------------------------------
    Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
        MyBase.OnPreRender(e)
        Dim loDirInfo As DirectoryInfo = New FileInfo(Request.PhysicalPath).Directory
        ClientScript.RegisterHiddenField("FocusCtl", "")
        Dim lsScript As StringBuilder

        'Set Dynamic pages to not save to disc
        Response.Buffer = True
        Response.ExpiresAbsolute = Now.AddMinutes(-1)
        Response.Expires = 0
        Response.CacheControl = "no-cache"


        lsScript = New StringBuilder
        lsScript.Append("<script language=""javascript"">" & vbCrLf)
        lsScript.Append("<!--" & vbCrLf)
        lsScript.Append("function ClearStatus(){ window.status = """";}" & vbCrLf)
        lsScript.Append("function Progress(){" & vbCrLf)
        lsScript.Append("		document.documentElement.style.cursor = ""wait"";" & vbCrLf)
        lsScript.Append("		window.status = ""Please wait..."";")
        lsScript.Append("}" & vbCrLf)
        lsScript.Append("//-->" & vbCrLf)
        lsScript.Append("</script>" & vbCrLf)
        ClientScript.RegisterClientScriptBlock(Me.GetType(), "Progress", lsScript.ToString)

        'ClientScript.RegisterOnSubmitStatement(Me.GetType(), "SubmitProgress", "return Progress();")

        lsScript = New StringBuilder

        lsScript.Append("<script language='javascript'>" & vbCrLf)
        lsScript.Append("<!--" & vbCrLf)
        lsScript.Append(" document.body.leftMargin = 0;" & vbCrLf)
        lsScript.Append("document.body.rightMargin = 0;" & vbCrLf)
        lsScript.Append("document.body.topMargin = 0;" & vbCrLf)
        lsScript.Append("document.body.bottomMargin = 0;" & vbCrLf)

        lsScript.Append(" window.status = '';" & vbCrLf)
        lsScript.Append(" document.documentElement.style.cursor = ""default"";" & vbCrLf)
        lsScript.Append("//-->" & vbCrLf)
        lsScript.Append("</script>" & vbCrLf)
        ClientScript.RegisterStartupScript(Me.GetType(), "Margins", lsScript.ToString)

        'set focus to first field
        lsScript = New StringBuilder
        lsScript.Append("<script language=javascript ><!--" & vbCrLf)
        lsScript.Append("var bFound = false;" & vbCrLf)
        lsScript.Append("for (f=0; f < document.forms.length; f++){" & vbCrLf)
        lsScript.Append("for(i=0; i < document.forms[f].length; i++){" & vbCrLf)
        lsScript.Append("if (document.forms[f][i].type != ""hidden""){" & vbCrLf)
        lsScript.Append("if (document.forms[f][i].disabled != true){" & vbCrLf)
        lsScript.Append("try{")
        lsScript.Append("document.forms[f][i].focus();" & vbCrLf)
        lsScript.Append("}catch (er){}")
        lsScript.Append("var bFound = true;}}" & vbCrLf)
        lsScript.Append("if (bFound == true)" & vbCrLf)
        lsScript.Append("break;}" & vbCrLf)
        lsScript.Append("if (bFound == true)" & vbCrLf)
        lsScript.Append("break;}" & vbCrLf)
        lsScript.Append("//--></script>" & vbCrLf)

    End Sub
    Public Function EncryptURL(ByVal psURL As String) As String
        If psURL.IndexOf("?") >= 0 Then
            Dim loCrypt As Encryption = New Encryption
            Return loCrypt.EncryptURL(psURL)
        Else
            Return psURL
        End If
    End Function
    Public Sub Redirect(ByVal psURL As String)
        Response.Redirect(EncryptURL(psURL))
    End Sub



End Class
Public Class cException
    Inherits System.Exception
    Private mPage As Page

    Public Property Page() As Page
        Get
            Return mPage
        End Get
        Set(ByVal Value As Page)
            mPage = Value
        End Set
    End Property
End Class

